﻿#region sql ef
//using Microsoft.AspNetCore.Mvc;
//using ApiManage.Svc.Filter;
//using ApiManage.Models.RequestModels;
//using ApiManage.Models.ResultModels;
//using ApiManage.Models.zyhModels;
//using ApiManage.Service.IService;
//using ApiManage.Service.Service;
//using Rhonin.Common;
//using Rhonin.Common.Entity.Enum;
//using Rhonin.Common.Entity.Exception;
//using Rhonin.Common.Entity.Result;
//using Rhonin.Common.Extentions;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Linq.Expressions;

//namespace ApiManage.Svc.Controllers
//{
//    /// <summary>
//    /// 授权
//    /// </summary>
//    [Route("api/[controller]")]
//    [ApiController]
//    public class AuthController : BaseController
//    {
//        private readonly ISysUserService _sysUserService = new SysUserService();
//        /// <summary>
//        /// 登录
//        /// </summary>
//        /// <param name="param">请求信息</param>
//        /// <returns></returns>
//        [Route("Login"), HttpPost]
//        public Result<UserLoginResult> Login(UserLogin param)
//        {
//            Expression<Func<SysUser, bool>> where = o => o.Mark == 1 && o.LoginName.Equals(param.Account) && o.LoginPwd.Equals(param.Pwd);
//            var user = _sysUserService.GetUser(where);
//            if (user == null)
//                throw new ApiException("用户不存在或密码错误");
//            var ticket = Ticket.SetTicket(user.UserId, user.UserName, Platform.Web);
//            return ApiResult<UserLoginResult>.TResult(new UserLoginResult
//            {
//                UserName = user.UserName,
//                RoleName = user.RoleName,
//                Ticket = ticket
//            });
//        }
//        /// <summary>
//        /// 获取登录用户信息
//        /// </summary>
//        /// <returns></returns>
//        [HttpGet, Route("GetLoginInfo"), CheckLogin]
//        public Result<SysUser> GetLoginInfo()
//        {
//            var user = _sysUserService.GetUser(o => o.UserId == _UserId);
//            var role = _sysUserService.GetRole(o => o.RoleId == user.RoleId);
//            List<string> roleMenu = new List<string>();
//            List<string> roleButton = new List<string>();
//            List<string> roleColumn = new List<string>();
//            if (role.RoleId == 0)
//            {
//                roleMenu = _sysUserService.GetMenu(o => o.Mark == 1).Select(o => o.MenuId.ToString()).ToList();
//                roleButton = _sysUserService.GetMenuButton(o => o.Mark == 1).Select(o => o.MenuButtonId.ToString()).ToList();
//                roleColumn = _sysUserService.GetMenuColumn(o => o.Mark == 1).Select(o => o.ColumnId.ToString()).ToList();
//            }
//            else
//            {
//                roleMenu = role.RoleMenu.Split(',').ToList();
//                roleButton = role.RoleButton.Split(',').ToList();
//                roleColumn = role.RoleColumn.Split(',').ToList();
//            }
//            user.RoleMenu = _sysUserService.GetMenu(o => roleMenu.Contains(o.MenuId.ToString())).Select(o => o.MenuUrl).ToList();
//            user.RoleButton = _sysUserService.GetMenuButton(o => roleButton.Contains(o.MenuButtonId.ToString())).Select(o => o.EnCode).ToList();
//            user.RoleColumn = _sysUserService.GetMenuColumn(o => roleColumn.Contains(o.ColumnId.ToString())).Select(o => o.EnCode).ToList();
//            user.Menus = GetMenu(user);
//            return ApiResult<SysUser>.TResult(user);
//        }

//        private List<SysMenu> GetMenu(SysUser user)
//        {
//            var menu = _sysUserService.GetMenu(o => user.RoleMenu.Contains(o.MenuUrl));
//            var topMenu = menu.Where(o => o.MenuUp == 0).OrderBy(o => o.Sort).ToList();
//            var i = 0;
//            foreach (var item in topMenu)
//            {
//                item.KeyStr = i.ToString();
//                GetChildren(item, menu);
//                i++;
//            }
//            return topMenu;
//        }

//        private SysMenu GetChildren(SysMenu menu, List<SysMenu> allMenu)
//        {
//            List<SysMenu> children = allMenu.Where(o => o.MenuUp == menu.MenuId).OrderBy(o => o.Sort).ToList();
//            if (children.Count <= 0) return menu;
//            int i = 1;
//            foreach (var item in children)
//            {
//                item.KeyStr = menu.KeyStr + "-" + i;
//                GetChildren(item, allMenu);
//                i++;
//            }
//            menu.Children = children;
//            return menu;
//        }
//    }
//}
#endregion

#region Mongo
using ApiManage.Models.MongoMappings.Sys;
using ApiManage.Models.RequestModels;
using ApiManage.Models.ResultModels;
using ApiManage.Svc.Filter;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using Rhonin.Common;
using Rhonin.Common.Entity.Enum;
using Rhonin.Common.Entity.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ApiManage.Service.Mongo.Sys;
using Rhonin.Common.Entity.Api;
using Rhonin.Common.Extentions;

namespace ApiManage.Svc.Controllers
{
    /// <summary>
    /// 授权
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : BaseController
    {
        private readonly ISysUserQueryService _sysUserQueryService;
        private readonly ISysMenuQueryService _sysMenuQueryService;
        private readonly ISysColumnQueryService _sysColumnQueryService;
        private readonly ISysButtonQueryService _sysButtonQueryService;
        private readonly ISysRoleQueryService _sysRoleQueryService;
        /// <summary>
        /// 
        /// </summary>
        public AuthController(ISysUserQueryService sysUserQueryService,
            ISysMenuQueryService sysMenuQueryService,
            ISysColumnQueryService sysColumnQueryService,
            ISysButtonQueryService sysButtonQueryService,
            ISysRoleQueryService sysRoleQueryService)
        {
            _sysUserQueryService = sysUserQueryService;
            _sysMenuQueryService = sysMenuQueryService;
            _sysColumnQueryService = sysColumnQueryService;
            _sysButtonQueryService = sysButtonQueryService;
            _sysRoleQueryService = sysRoleQueryService;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="param">请求信息</param>
        /// <returns></returns>
        [Route("Login"), HttpPost]
        public ApiResult<UserLoginResult> Login(UserLogin param)
        {
            Expression<Func<SysUser, bool>> where = o => o.Mark == 1 && o.LoginName.Equals(param.Account) && o.LoginPwd.Equals(param.Pwd);
            var user = _sysUserQueryService.Get(where);
            if (user == null)
                throw new ApiException("用户不存在或密码错误");
            var ticket = Ticket.SetTicket(user.Id.ToString(), user.UserName, Platform.Web);
            return CreateResult(new UserLoginResult
            {
                UserName = user.UserName,
                RoleName = user.RoleName,
                Ticket = ticket
            });
        }
        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetLoginInfo"), CheckLogin]
        public ApiResult<SysUser> GetLoginInfo()
        {
            var user = _sysUserQueryService.Get(o => o.Id == new ObjectId(_UserId));
            if (user == null)
            {
                throw new ApiException("用户信息不存在");
            }
            var role = _sysRoleQueryService.Get(o => o.Id == new ObjectId(user.RoleId));
            if (role?.RoleMenuIds == null)
            {
                throw new ApiException("该用户无权限");
            }
            var userMenuIds = new List<ObjectId>();
            var userButtonIds = new List<ObjectId>();
            var userColumnIds = new List<ObjectId>();
            role.RoleMenuIds.ForEach(o => { userMenuIds.Add(new ObjectId(o)); });
            role.RoleButtonIds.ForEach(o =>
            {
                if (!o.Contains("_button"))
                {
                    userButtonIds.Add(new ObjectId(o));
                }
            });
            role.RoleColumnIds.ForEach(o =>
            {
                if (!o.Contains("_column"))
                {
                    userColumnIds.Add(new ObjectId(o));
                }
            });
            user.UserRole = _sysMenuQueryService.GetList(o => userMenuIds.Contains(o.Id));
            user.UserButton = _sysButtonQueryService.GetList(o => userButtonIds.Contains(o.Id));
            user.UserColumn = _sysColumnQueryService.GetList(o => userColumnIds.Contains(o.Id));
            user.UserMenu = GetUserMenuTree(user.UserRole);
            return CreateResult(user);
        }

        private List<MenuTree> GetUserMenuTree(List<SysMenu> userMenus)
        {
            var topMenu = userMenus.Where(o => o.MenuUp.IsNullOrEmpty()).OrderBy(o => o.Sort).Select(o => new MenuTree
            {
                Id = o.Id.ToString(),
                Title = o.MenuName,
                Icon = o.MenuIcon,
                Path = o.MenuUrl
            }).ToList();
            foreach (var item in topMenu)
            {
                GetMenuChildren(item, userMenus);
            }
            return topMenu;
        }

        private void GetMenuChildren(MenuTree menu, List<SysMenu> allMenus)
        {
            var childrenMenu = allMenus.Where(o => o.MenuUp == menu.Id).OrderBy(o => o.Sort).Select(o => new MenuTree
            {
                Id = o.Id.ToString(),
                Title = o.MenuName,
                Icon = o.MenuIcon,
                Path = o.MenuUrl
            }).ToList();
            if (childrenMenu.Count <= 0) return;
            foreach (var item in childrenMenu)
            {
                GetMenuChildren(item, allMenus);
            }
            menu.Children = childrenMenu;
        }
    }
}
#endregion